<template>
  <div class="businessCenter animated bounceInRight">
    <div class="businessCenter-header">
      <div
        v-for="(item) in headerInfo"
        :key="item.key"
        class="businessCenter-header-item "
        :style="{
          'background-image': `url(${item.img})`,
          'background-size': '100% 100%'
        }"
      >
        <div v-show="headerInfoAnimate" :class="`businessCenter-header-item-info ${headerInfoAnimate && 'animated bounceInDown'}`">
          <div :class="`businessCenter-header-value`">
            {{ item.value }}
          </div>
          <div :class="`businessCenter-header-title`">
            {{ item.title }}
          </div>

        </div>
      </div>
    </div>

    <div class="businessCenter-container ">
      <div class="businessCenter-tabs">
        <el-tabs v-model="activeTab" @tab-click="tabClick">
          <el-tab-pane
            v-for="(item, index) in bussinessTaps"
            :key="index"
            :name="index + ''"
          >
            <span slot="label" class="tabBox"><i v-if="g=headerInfo[index].title==='待办数'&&headerInfo[index].value!==0" class="dot">{{ headerInfo[index].value>99?'99+':headerInfo[index].value }}</i>{{ item.title }}</span>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div ref="tableContainer" class="businessCenter-table">
        <Business-Table
          ref="bus-table"
          :form="form"
          :class="form.formClass"
        />
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  getApplyTaskList,
  getTodoTaskList,
  getApproveList,
  getDraft,
  getCount,
  getSidByDefKey
} from '@/api/table';
import BusinessTable from '@/views/businessCenterPage/components/BusinessTable';

const mapStatus = {
  running: {
    label: '运行中',
    color: '#2998FF'
  },
  end: {
    label: '结束',
    color: '#FAB01C'
  },
  back: {
    label: '驳回',
    color: '#898BE4'
  },
  NORMAL: {
    label: '运行中',
    color: '#2998FF'
  },
  BACK: {
    label: '驳回',
    color: '#898BE4'
  }
};

export default {
  components: { BusinessTable },

  data() {
    return {
      headerInfo: [
        {
          title: '申请数',
          key: 'sq',
          value: 0,
          img: require('@/assets/img/bussinessCenter/申请数.png')
        },
        {
          title: '待办数',
          key: 'db',
          value: 0,
          img: require('@/assets/img/bussinessCenter/待办数.png')
        },
        {
          title: '已办数',
          key: 'yb',
          value: 0,
          img: require('@/assets/img/bussinessCenter/已办数.png')
        },
        {
          title: '暂存数',
          key: 'zc',
          value: 0,
          img: require('@/assets/img/bussinessCenter/暂存数.png')
        }
      ],
      headerInfoAnimate: false,
      activeTab: '',
      bussinessTaps: [
        {
          title: '我的申请'
        },
        {
          title: '我的待办'
        },
        {
          title: '我的已办'
        },
        {
          title: '我的草稿'
        }
      ],

      form: {
        formClass: '',
        colunms: [],
        data: [],
        height: 0,
        isLoading: false,
        request: {
          pageSize: 20,
          pageIndex: 1,
          searchSubject: '',
          total: 0
        },
        pageChange: (data) => {
          const { pageSize, currentPage } = data;
          if (pageSize !== this.form.request.pageSize) {
            this.form.request.pageSize = pageSize;
            this.form.request.pageIndex = 1;
          } else {
            this.form.request.pageIndex = currentPage;
          }

          this.sendRequest(this.requestData);
        }
      }
    };
  },

  computed: {
    // 请求参数
    requestData() {
      const data = this.form.request;
      // 草稿
      if (this.activeTab === '3') {
        return {
          userId: this.userId,
          pageIndex: data.pageIndex,
          pageSize: data.pageSize
        };
      } else {
        return {
          order: 'asc',
          offset: (data.pageIndex - 1) * data.pageSize,
          limit: data.pageSize,
          'task.subject_^VLK': data.searchSubject
        };
      }
    },

    userId() {
      return localStorage.getItem('xcUserId');
    },

    getData() {
      const map = {
        0: getApplyTaskList, // 申请
        1: getTodoTaskList, // 待办
        2: getApproveList, // 已办
        3: getDraft // 草稿
      };

      if (this.activeTab in map) {
        return map[this.activeTab];
      } else {
        return () => {
          throw new Error('没有' + this.bussinessTaps[this.activeTab * 1].title + '的对应方法');
        };
      }
    }
  },

  mounted() {
    this.activeTab = (this.$route.query.type && this.$route.query.type + '') || '1';
    this.form.height = this.$refs.tableContainer.offsetHeight - 30;
    this.tabClick();
    this.getCount();
  },

  methods: {
    // 获取申请数、待办数
    getCount() {
      return getCount({ userId: this.userId }).then(res => {
        setTimeout(() => {
          this.headerInfoAnimate = true;
        }, 500);

        if (res.success) {
          const data = res.data;
          data.forEach((item, index) => {
            this.headerInfo[index].value = item.total;
          });
        }
      });
    },

    tabClick() {
      this.form.formClass = 'animated fadeIn';
      setTimeout(() => {
        this.form.formClass = '';
      }, 500);
      this.form.request.pageIndex = 1;

      this.sendRequest(this.requestData);
      this.form.colunms = this.getTableColunms();
      this.getCount();
    },

    sendRequest(data) {
      this.form.isLoading = true;
      return this.getData(data).then(res => {
        this.form.isLoading = false;
        if (res.success) {
          this.form.data = res.data;
          this.form.request.total = res.total;
          return Promise.resolve(res);
        } else {
          this.form.data = [];
          this.form.request.total = 0;
        }
      });
    },
    commonDo(row, flag) {
      let key = '';
      if (flag === 0) {
        key = row.key;
      } else {
        key = row.defKey;
      }
      getSidByDefKey({
        key: key
      }).then(res => {
        if (res.success) {
          if (flag === 0) {
            const param = {
              path: res.data.path,
              query: {
                subject: row.topic,
                title: row.topic.split('发起')[1],
                sId: row.sId,
                formGuid: row.formGuid,
                key: row.key,
                defId: row.id,
                flag: flag,
                fileType: row.fileType,
                isHideLeft: 0,
                isHideTop: 1
                // isShow: true
              }
            };
            const routeUrl = this.$router.resolve(param);
            const tempwindow = window.open('_blank'); // 先打开页面
            tempwindow.location = routeUrl.href; // 后更改页面地址
          } else {
            const param = {
              path: res.data.path,
              query: {
                subject: row.subject,
                title: row.subject.split('发起')[1],
                sId: res.data.sId,
                formGuid: row.bizKey,
                defId: row.defId,
                instId: row.instId,
                taskId: row.taskId,
                nodeId: row.nodeId,
                flag: flag,
                fileType: res.data.fileType,
                signName: row.status,
                isHideLeft: 0,
                isHideTop: 1

              }
            };
            const routeUrl = this.$router.resolve(param);
            const tempwindow = window.open('_blank'); // 先打开页面
            tempwindow.location = routeUrl.href; // 后更改页面地址
          }
        } else {
          this.$message({
            type: 'warning',
            message: '该事项的流程有问题'
          });
        }
      });
    },

    // table 操作
    operatorClick(row, type) {
      const eventMap = {
        0: (row) => {
          // 我的申请
          this.commonDo(row, 1);
        },
        1: (row) => {
          // 我的待办
          this.commonDo(row, 2);
        },
        2: (row) => {
          // 我的已办
          this.commonDo(row, 1);
        },
        3: (row) => {
          // 我的草稿
          this.commonDo(row, 0);
        }
      };

      if (type in eventMap) {
        eventMap[type](row);
      }
    },

    // 表头
    getTableColunms() {
      const map = {
        0: [
          { type: 'seq', width: 60, title: '序号' },
          {
            title: '环节状态', width: 100, slots: {
              default: ({ row }) => {
                const map = mapStatus;
                const item = map[row.status];
                return [
                  <div>
                    {
                      item ? (
                        [
                          <span
                            style={
                              {
                                color: item.color
                              }
                            }
                          >
                            {item.label}
                          </span>
                        ]
                      )
                        : (
                          [
                            <span>
                            未定义：{row.status}的状态
                            </span>
                          ]
                        )
                    }
                  </div>
                ];
              }
            }
          },
          { field: 'assigneeNames', title: '当前审核人' },
          { field: 'subject', title: '主题', minWidth: 300 },
          { field: 'creator', title: '创建人', width: 100 },
          { title: '创建时间', slots: {
            default: ({ row }) => {
              return (
                [
                  <div>
                    {
                      row.createTime.split(' ')[0]
                    }
                  </div>
                ]
              );
            }
          }
          },
          { title: '结束时间', slots: {
            default: ({ row }) => {
              return (
                [
                  <div>
                    {
                      row.endTime && row.endTime.split(' ')[0]
                    }
                  </div>
                ]
              );
            }
          }
          },
          {
            title: '操作', width: 100, slots: {
              default: ({ row }) => {
                const { operatorClick, activeTab } = this;
                return (
                  [
                    <div class='table-operator'>
                      <span onclick={() => operatorClick(row, activeTab)}>查看</span>
                      <span>撤回</span>
                    </div>
                  ]
                );
              }
            }
          }
        ],
        1: [
          { type: 'seq', width: 60, title: '序号' },
          {
            title: '环节状态', width: 100, slots: {
              default: ({ row }) => {
                const map = mapStatus;
                const item = map[row.status];
                return [
                  <div>
                    {
                      item ? (
                        [
                          <span
                            style={
                              {
                                color: item.color
                              }
                            }
                          >
                            {item.label}
                          </span>
                        ]
                      )
                        : (
                          [
                            <span>
                            未定义：{row.status}的状态
                            </span>
                          ]
                        )
                    }
                  </div>
                ];
              }
            }
          },
          { field: 'assigneeNames', title: '当前审核人' },
          { field: 'subject', title: '主题', minWidth: 300 },
          { field: 'creator', title: '创建人', width: 100 },
          { title: '创建时间', slots: {
            default: ({ row }) => {
              return (
                [
                  <div>
                    {
                      row.createTime.split(' ')[0]
                    }
                  </div>
                ]
              );
            }
          }
          },
          { title: '结束时间', slots: {
            default: ({ row }) => {
              return (
                [
                  <div>
                    {
                      row.endTime && row.endTime.split(' ')[0]
                    }
                  </div>
                ]
              );
            }
          }
          },
          {
            title: '操作', width: 100, slots: {
              default: ({ row }) => {
                const { operatorClick, activeTab } = this;
                return (
                  [
                    <div class='table-operator'>
                      <span onclick={() => operatorClick(row, activeTab)}>去办理</span>
                    </div>
                  ]
                );
              }
            }
          }
        ],
        2: [
          { type: 'seq', width: 60, title: '序号' },
          {
            title: '环节状态', width: 100, slots: {
              default: ({ row }) => {
                const map = mapStatus;
                const item = map[row.status];
                return [
                  <div>
                    {
                      item ? (
                        [
                          <span
                            style={
                              {
                                color: item.color
                              }
                            }
                          >
                            {item.label}
                          </span>
                        ]
                      )
                        : (
                          [
                            <span>
                            未定义：{row.status}的状态
                            </span>
                          ]
                        )
                    }
                  </div>
                ];
              }
            }
          },
          { field: 'assigneeNames', title: '当前审核人' },
          { field: 'subject', title: '主题', minWidth: 300 },
          { field: 'creator', title: '创建人', width: 100 },
          { title: '创建时间', slots: {
            default: ({ row }) => {
              return (
                [
                  <div>
                    {
                      row.createTime.split(' ')[0]
                    }
                  </div>
                ]
              );
            }
          }
          },
          { title: '结束时间', slots: {
            default: ({ row }) => {
              return (
                [
                  <div>
                    {
                      row.endTime && row.endTime.split(' ')[0]
                    }
                  </div>
                ]
              );
            }
          }
          },
          {
            title: '操作', width: 100, slots: {
              default: ({ row }) => {
                const { operatorClick, activeTab } = this;
                return (
                  [
                    <div class='table-operator'>
                      <span onclick={() => operatorClick(row, activeTab)}>查看</span>
                    </div>
                  ]
                );
              }
            }
          }
        ],
        3: [
          { type: 'seq', width: 60, title: '序号' },
          { field: 'topic', title: '主题', minWidth: 300 },
          { title: '创建时间', slots: {
            default: ({ row }) => {
              return (
                [
                  <div>
                    {
                      row.createTime.split(' ')[0]
                    }
                  </div>
                ]
              );
            }
          }
          },
          {
            title: '操作', width: 100, slots: {
              default: ({ row }) => {
                const { operatorClick, activeTab } = this;
                return (
                  [
                    <div class='table-operator'>
                      <span onclick={() => operatorClick(row, activeTab)}>继续编辑</span>
                    </div>
                  ]
                );
              }
            }
          }
        ]
      };
      const tab = this.activeTab;
      if (tab in map) {
        return map[tab];
      } else {
        return [];
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.businessCenter {
  width: 100%;
  height: 100%;
  padding: 12px 24px;
  display: flex;
  flex-direction: column;

  .businessCenter-header {
    display: flex;
    gap: 0 25px;
    > div {
      flex: 1;
      height: 140px;

      .businessCenter-header-item-info {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 30px;

        > div {
          text-align: center;
          width: 150px;
        }

        .businessCenter-header-value {
            font-size: 40px;
            color: #faad14;
        }

        .businessCenter-header-title {
          font-size: 18px;
          color: #666666;
        }
      }
    }
  }

  .businessCenter-container {
    margin-top: 12px;
    flex: 1;
    padding: 12px;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    .businessCenter-table {
      flex: 1;
    }
  }

  .table-operator {
    display: flex;
    justify-content: space-between;
    padding-right: 10px;
    color: #1890FF;
    > span {
      cursor: pointer;
      text-decoration: underline;
    }
  }
}
.tabBox{
  position: relative;
  display: block;
}
.dot{
  position: absolute;
  background-color: #f56c6c;
    border-radius: 10px;
    color: #fff;
    display: inline-block;
    font-size: 12px;
    height: 14px;
    line-height: 14px;
    padding: 0 4px;
    text-align: center;
    white-space: nowrap;
    font-style: normal;
    right: -7px;
    top: 3px;
}
</style>
